class KeyboardController {
  constructor(socket) {
      this.socket = socket;
      this.keyStates = {};
      this.velocity = { linear: 0, angular: 0 };
      this.maxLinear = 1.0;  // m/s
      this.maxAngular = 1.57; // rad/s
      this.acceleration = 0.1;
      
      // 初始化事件监听
      this.initEventListeners();
      
      // 开始控制循环
      this.controlLoop();
  }
  
  initEventListeners() {
      document.addEventListener('keydown', (e) => {
          if (!this.keyStates[e.key]) {
              this.keyStates[e.key] = true;
              this.handleKeyChange();
          }
      });
      
      document.addEventListener('keyup', (e) => {
          this.keyStates[e.key] = false;
          this.handleKeyChange();
      });
  }
  
  handleKeyChange() {
      // 重置速度
      this.velocity = { linear: 0, angular: 0 };
      
      // 前进/后退
      if (this.keyStates['w'] || this.keyStates['ArrowUp']) {
          this.velocity.linear = this.maxLinear;
      } else if (this.keyStates['s'] || this.keyStates['ArrowDown']) {
          this.velocity.linear = -this.maxLinear * 0.5;
      }
      
      // 左转/右转
      if (this.keyStates['a'] || this.keyStates['ArrowLeft']) {
          this.velocity.angular = this.maxAngular;
      } else if (this.keyStates['d'] || this.keyStates['ArrowRight']) {
          this.velocity.angular = -this.maxAngular;
      }
      
      // 组合键处理
      if ((this.keyStates['w'] || this.keyStates['ArrowUp']) && 
          (this.keyStates['a'] || this.keyStates['ArrowLeft'])) {
          this.velocity.linear = this.maxLinear * 0.7;
          this.velocity.angular = this.maxAngular * 0.7;
      } else if ((this.keyStates['w'] || this.keyStates['ArrowUp']) && 
                (this.keyStates['d'] || this.keyStates['ArrowRight'])) {
          this.velocity.linear = this.maxLinear * 0.7;
          this.velocity.angular = -this.maxAngular * 0.7;
      }
  }
  
  controlLoop() {
      // 平滑发送速度命令
      const sendCommand = () => {
          if (this.velocity.linear !== 0 || this.velocity.angular !== 0) {
              this.socket.emit('velocity_command', this.velocity);
          }
          requestAnimationFrame(sendCommand);
      };
      
      sendCommand();
  }
}